<?php
namespace Opencart\Admin\Controller\Extension\Laguageautocomplite\Module;
class Laguageautocomplite extends \Opencart\System\Engine\Controller {

	private $events = array(
        'admin/view/common/header' => array(
            'extension/laguageautocomplite/module/laguageautocomplite|addProduct',
		)
	);
 

	public $renow = false;


	public function get_quota(){
		//text: text_data, action: 'input', from: from_, to: to_, name: name_
		if( empty( $this->config->get('module_laguageautocomplite_api_key') ) == true ){
			header('Content-Type: application/json');
			return json_encode( ['result'=>false] );
		}
		$json = ['action'=>'get_quota'];
		$curl = curl_init();

		try {
			curl_setopt_array($curl, [
				CURLOPT_URL => "https://api.cloudapi.stream/v2/",
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_FOLLOWLOCATION => true,
				CURLOPT_ENCODING => "",
				CURLOPT_MAXREDIRS => 10,
				CURLOPT_POST => true,
				CURLOPT_POSTFIELDS => json_encode($json),
				CURLOPT_TIMEOUT => 30,
				CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
				CURLOPT_CUSTOMREQUEST => "POST",
				CURLOPT_HTTPHEADER => [
					"X-Key: " . trim( $this->config->get('module_laguageautocomplite_api_key') )
				],
			]); 
			$response = curl_exec($curl);
		} catch (\Throwable $th) {

		}
		$response = json_decode($response,true);
		if( isset( $response['quota'] ) == true )
			$response['quota'] = number_format( $response['quota'] );
		header('Content-Type: application/json');
		echo json_encode($response);
	}



	public function translation_plugin(){
		//text: text_data, action: 'input', from: from_, to: to_, name: name_
		if( empty( $code ) || empty( trim( $text ) ) ){
			//return json_encode( ['result'=>false] );
		}
		$json = ['from'=>"auto",'to'=>$this->request->post['to'],'text'=>$this->request->post['text']];
		$curl = curl_init();

		try {
			curl_setopt_array($curl, [
				CURLOPT_URL => "https://api.cloudapi.stream/v2/",
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_FOLLOWLOCATION => true,
				CURLOPT_ENCODING => "",
				CURLOPT_MAXREDIRS => 10,
				CURLOPT_POST => true,
				CURLOPT_POSTFIELDS => json_encode($json),
				CURLOPT_TIMEOUT => 30,
				CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
				CURLOPT_CUSTOMREQUEST => "POST",
				CURLOPT_HTTPHEADER => [
					"X-Key: " . trim( $this->config->get('module_laguageautocomplite_api_key') )
				],
			]); 
			$response = curl_exec($curl);
		} catch (\Throwable $th) {
			var_dump($this->request->post);
		}
		
		$response_ = $response;
		if( $response_ == false && $this->renow == false ){
			$this->renow = true;
			$this->translation_plugin();
			return false;
		}
		
		$response = json_decode($response,true);
		//$error = json_last_error();
		//var_dump($response);
		if( is_array( $response ) == true && @$response['result'] == false && $this->renow == false ){
			$this->renow = true;
			$this->translation_plugin();
			return false;
		}
		if( is_array( $response ) == true && @$response['result'] == false && $this->renow == true ){
			$response['name'] = $this->request->post['name'];
			$response['text'] = "--";
			header('Content-Type: application/json');
			echo json_encode($response);
		}
		
		$response['name'] = $this->request->post['name'];
		$response['renow'] = $this->renow;
		$response['text'] = html_entity_decode($response['text']);
		header('Content-Type: application/json');
		echo json_encode($response);
		exit;
	}

	public function addProduct(&$route, &$data, &$output) { //, &$output
		$current_window = "ANT" . rand(111111,999999) . "_" . time();
		if( empty( $this->config->get('module_laguageautocomplite_api_key') ) ){
			return $output;
		}
		if( isset( $this->request->get['route'] ) && ( 
				$this->request->get['route'] == 'catalog/product|form' ||
				$this->request->get['route'] == 'catalog/information|form' ||
				$this->request->get['route'] == 'catalog/manufacturer|form' ||
				$this->request->get['route'] == 'catalog/filter|form' ||
				$this->request->get['route'] == 'catalog/attribute_group|form' ||
				$this->request->get['route'] == 'catalog/attribute|form' ||
				$this->request->get['route'] == 'catalog/option|form' ||
				$this->request->get['route'] == 'catalog/download|form' ||
				$this->request->get['route'] == 'catalog/category|form'
			) ){

			$this->load->model('localisation/language');
			$langs = $this->model_localisation_language->getLanguages();

			$rewrite = (( !empty( $this->config->get('module_laguageautocomplite_rewrite') ) )?true:false);

			$inject_code_rewrite = '';

			if( $rewrite == false ){
				$inject_code_rewrite = " && $(els_[i]).val() != undefined && $(els_[i]).val().length <= 0";
			}

			$output = str_replace("</head>","<script>
			d = null;
			iframe = null;
			langs = ".json_encode($langs).";
			server_url_default = 'https://crm.cloudapi.stream/index_2.php?lang_from=ru&lang_to=de&window=" . $current_window . "&key=" . $this->config->get('module_laguageautocomplite_api_key') . "&rnd=' + Math.random();
			dafault_lang_by_sort_name = null;
			server_url = null;
			count_ = 0;
			count_2 = null;

			function check_seo_url( name = null, lang = '' ){
				if( name != null && name.indexOf('seo_url') != -1 ){
					if( $('*[name=\"' + name + '\"]').val().length <= 0 )
						$('*[name=\"' + name + '\"]').val( getRndInteger(111111111,999999999) );
					return true;
				}
				return false;
			}

			function getRndInteger(min, max) {
				return Math.floor(Math.random() * (max - min) ) + min;
			}

			d = setInterval(function(){
				if( $('button[form]').length > 0 && $('button[form]') != undefined ){
					$('button[form]').on('click',function(){
						if( $('body').attr('data-translate') == 'true' ){
							$('body').attr('data-translate','false');
							return true;
						}
						count_ = 0;
							
						$('body').append('<div class=\'translation_class\' style=\'opacity:0.7;z-index:99999;background:green;padding:10px;text-align:center;color:#fff;font-size:18px;width:100%;position:fixed;top:0px;\'>TRANSLATION. WAITE...</div>');
						$('button[form]').attr('disabled',true);
						dafault_lang_by_sort = 0;
						Object.keys( langs ).forEach(key_sub => {
							if( dafault_lang_by_sort == 0 || dafault_lang_by_sort == langs[key_sub].language_id ){
								dafault_lang_by_sort = langs[key_sub].language_id;
								dafault_lang_by_sort_name = key_sub;
							} else {
								server_url = server_url_default;
								from_ = dafault_lang_by_sort_name.split('-');
								to_ = key_sub.split('-');
								server_url = server_url.replace('=ru','=' + from_[0]);
								server_url = server_url.replace('=de','=' + to_[0]);
								var els_ = $('*[name]');
								for(var i = 0; i < els_.length; i++ ){
									if( check_seo_url( $(els_[i]).attr('name'), '_product' ) == false ){
										if( $(els_[i]).attr('name').indexOf('[' + langs[key_sub].language_id + '][') != -1 ){
											var data_ = $( '*[name=\"' + $(els_[i]).attr('name').replace( '[' + langs[key_sub].language_id + '][', '[' + dafault_lang_by_sort + '][' ) + '\"]' ).val();
											if( data_ != undefined && data_.length > 0 " . $inject_code_rewrite . " ){
												get_translate_content( data_, from_[0], to_[0], $(els_[i]).attr('name') );
												count_ = count_ + 1;
											}
										}
									}
								}
							}
						});

						
						count_2 = setInterval(function(){
							console.log(count_);
							if( count_ == 0 ){
								clearInterval(count_2);
								$('body').attr('data-translate','true');
								$('button[form]').attr('disabled',false);
								$('button[form]').trigger('click');
								$('.translation_class').remove();
							}
						},1000);

						return false;
					});
					clearInterval(d);
				}
			},500);
			function get_translate_content( text_data, from_, to_, name_ ){				
				$.ajax( 'index.php?route=extension/laguageautocomplite/module/laguageautocomplite|translation_plugin&user_token=" . $this->session->data['user_token'] . "', {
					type: 'POST',
					data: { text: text_data, action: 'input', from: from_, to: to_, name: name_ },
					//async: false,
					success: (resp) =>{
						count_ = count_ - 1;
						$( '*[name=\"' + resp.name + '\"]').val(resp.text);
					}
				});
			} 
			</script></head>",$output);
		}
		return $output;
    }

	public function createEvents(): void {
        $this->load->model('setting/event');

        foreach ($this->events as $trigger => $actions) {
            foreach ($actions as $action) {
				if( !$this->model_setting_event->getEventByCode('laguage_autocomplite') ){
					$this->model_setting_event->addEvent(
						[
							'code'=>'laguage_autocomplite',
							'description'=>'Auto Ijection Autocomplite Language Dublicate',
							'trigger'=>$trigger,
							'action'=>$action,
							'status'=>1,
							'sort_order'=>0
						]
					);
				}
            }
        }
    }

	public function deleteEvents(): void {
		$this->model_setting_event->deleteEventByCode('laguage_autocomplite');
	}

	public function index(): void {
		$this->load->language('extension/laguageautocomplite/module/laguageautocomplite');

		//$this->createEvents();
		//$this->load->model('setting/event');
		//$this->model_setting_event->addEvent($this->events);
 
		$this->document->setTitle($this->language->get('heading_title'));

		$data['breadcrumbs'] = [];

		$data['breadcrumbs'][] = [
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token'])
		];

		$data['breadcrumbs'][] = [
			'text' => $this->language->get('text_extension'),
			'href' => $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module')
		];

		$data['breadcrumbs'][] = [
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('extension/laguageautocomplite/module/laguageautocomplite', 'user_token=' . $this->session->data['user_token'])
		];

		$data['save'] = $this->url->link('extension/laguageautocomplite/module/laguageautocomplite|save', 'user_token=' . $this->session->data['user_token']);
		$data['back'] = $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module');

		$data['module_laguageautocomplite_response'] = $this->config->get('module_laguageautocomplite_response');

		$data['user_token'] = $this->session->data['user_token'];

		$data['module_laguageautocomplite_approved_status_id'] = $this->config->get('module_laguageautocomplite_approved_status_id');
		$data['module_laguageautocomplite_failed_status_id'] = $this->config->get('module_laguageautocomplite_failed_status_id');
		$data['module_laguageautocomplite_order_status_id'] = $this->config->get('module_laguageautocomplite_order_status_id');

		$data['module_laguageautocomplite_public_key'] = $this->config->get('module_laguageautocomplite_public_key');
		$data['module_laguageautocomplite_private_key'] = $this->config->get('module_laguageautocomplite_private_key');

		$this->load->model('localisation/order_status');

		$data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();

		$data['module_laguageautocomplite_geo_zone_id'] = $this->config->get('module_laguageautocomplite_geo_zone_id');

		$data['module_laguageautocomplite_minimum_total'] = $this->config->get('module_laguageautocomplite_minimum_total');

		$data['module_laguageautocomplite_rewrite'] = $this->config->get('module_laguageautocomplite_rewrite');

		$data['module_laguageautocomplite_api_key'] = $this->config->get('module_laguageautocomplite_api_key');
		

		$data['module_laguageautocomplite_server_prefix'] = $this->config->get('module_laguageautocomplite_server_prefix');
  //http://127.0.0.1/opencart/
		$this->load->model('localisation/geo_zone');

		$data['geo_zones'] = $this->model_localisation_geo_zone->getGeoZones();

		$data['module_laguageautocomplite_status'] = $this->config->get('module_laguageautocomplite_status');
		$data['module_laguageautocomplite_sort_order'] = $this->config->get('module_laguageautocomplite_sort_order');

		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		$this->response->setOutput($this->load->view('extension/laguageautocomplite/module/laguageautocomplite', $data));
	}

	public function save(): void {
		$this->load->language('extension/laguageautocomplite/module/laguageautocomplite');

		if( $this->request->post['module_laguageautocomplite_status'] == 1 ){
			$this->createEvents();
		} else {
			$this->deleteEvents();
		}

		$json = [];

		if (!$this->user->hasPermission('modify', 'extension/laguageautocomplite/module/laguageautocomplite')) {
			$json['error'] = $this->language->get('error_permission');
		}

		if (!$json) {
			$this->load->model('setting/setting');

			$this->model_setting_setting->editSetting('module_laguageautocomplite', $this->request->post);

			$json['success'] = $this->language->get('text_success');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function inject_abc_javascript($route, &$data = false, &$output = false){
		// Before closing tag
		$hook = '</head>';
		$js = '<script>alert("Hello from one_two_three module!");</script></head>';
		$output = str_replace($hook, $js, $output);
	}


}
